//
//  BarButtonItem.swift
//  CooperSwift
//
//  Created by 计海峰 on 2022/9/27.
//

import Foundation
import RxSwift

public extension UIBarButtonItem {
    
    /// 按钮[UIBarButtonItem]
    /// - Parameters:
    ///   - texts: 标题
    ///   - font: font
    ///   - textColor: textColor
    ///   - debounce: 防止重复点击 RxTimeInterval
    ///   - method: 回调方法
    /// - Returns:[UIBarButtonItem]
    static func barItems(texts: [String], font: UIFont = .systemFont(ofSize: 15), textColor: UIColor = UIColor(hex: "#333333"), debounce: RxTimeInterval? = nil, method: ((_ sender: UIButton) -> Void)? = nil) -> [UIBarButtonItem] {
        var barButtonItem:[UIBarButtonItem] = []
        texts.forEach { title in
            var minWidth = title.getStringWidth(font) + 8
            minWidth = minWidth > 38 ? minWidth : 38
            let btn = UIButton(type: .custom).then {
                $0.frame = CGRect(0, 0, minWidth, 33)
                $0.setTitle(title, for: .normal)
                $0.titleLabel?.font = font
                $0.setTitleColor(textColor, for: .normal)
                if let method = method {
                    let sender = $0
                    if let debounce = debounce {
                        let _ = $0.rx.tap.asObservable().debounce(debounce, scheduler: MainScheduler.instance).subscribe(onNext: { _ in
                            method(sender)
                        })
                    }else {
                        let _ = $0.rx.tap.subscribe { _ in
                            method(sender)
                        }
                    }
                }
            }
            barButtonItem.append(UIBarButtonItem(customView: btn))
        }
        return barButtonItem
    }
    
}
